<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php


class MRestoreController
extends MApplicationComponent
implements MIController
{
    private $_root      = null;
    private $_user_id   = null;
    
    public function invoke($uri=null)
    {
                                parent::init();
        $params = $_REQUEST;
                if (isset($params) === false || $params == null) {
            throw new MAuthorizationException(FXP::t('Invalid parameters'));
        }
        
                                $locale = "bytes";
        if (isset($params["locale"])) {
            $locale = $params["locale"];
        }
        $url                = $uri;
        $url_manager = new MUrlManager();
        $this->_root        = $url_manager->parseRootFromUrl($uri);
        $path               = $url_manager->parsePathFromUrl($uri);
        $path         = MUtils::convertStandardPath($path);
        $originalPath = $path;
                        $user   = MUserManager::getInstance()->getCurrentUser();
        $device = MUserManager::getInstance()->getCurrentDevice();
        $this->_user_id     = $user->user_id;
        $user_nick          = $user->user_name;
        $user_device_id   = $device->device_id;
        
        $rev                = $params["rev"];
        $rev                = intval($rev);
        $path               = "/{$this->_user_id}{$path}";
        
                                $file_meta = MFileMetas::queryFileMeta($path, MConst::VERSION);
        if ($file_meta == false || empty($file_meta)) {
            throw new MFileopsException(
                                        FXP::t('    Unable to find the revision at that path'),
                                        MConst::HTTP_CODE_404);
        }
        
        if (MUtils::isExistReversion($rev, $file_meta[0]["meta_value"]) == false) {
            throw new MFileopsException(
                                        FXP::t('    Unable to find the revision at that path'),
                                        MConst::HTTP_CODE_404);
        }
        
                                $version = MFileVersions::queryFileVersionByID($rev);
        if ($version === false || empty($version))
        {
            throw new MFileopsException(
                                        FXP::t('    Unable to find the revision at that path'),
                                        MConst::HTTP_CODE_404);
        }
        $size = $version[0]["file_size"];
        $file_hash = $version[0]["file_signature"];
                                $query_db_file = MFiles::queryFilesByPath($path);
        if ($query_db_file === false || empty($query_db_file))
        {
            throw new MFileopsException(
                                        FXP::t('not existed'),
                                        MConst::HTTP_CODE_404);
        }
        if ($query_db_file[0]["file_type"] == MConst::OBJECT_TYPE_DIRECTORY)
        {
                        throw new MFileopsException(
                                        FXP::t('folder not existed version'),
                                        MConst::HTTP_CODE_403);
        }
        if ($rev !== $query_db_file[0]["version_id"])
        {
                                                $updates = array();
            $updates["version_id"]          = $rev;
            $updates["file_update_time"]    = time();
            $updates["file_size"]           = $size;
            $ret = MFiles::updateFileDetailById($query_db_file[0]["id"], $updates);
            if ($ret === false)
            {
                throw new MFileopsException(
                                            FXP::t('Internal Server Error'),
                                            MConst::HTTP_CODE_500);
            }
            $file_detail = new MFiles();
            $file_detail->file_name         = $query_db_file[0]["file_name"];
            
                                                $ret = MEvents::CreateEvents( $this->_user_id, 
                                          $user_device_id, 
                                          MConst::MODIFY_FILE,
                                          $file_detail->path,
                                          $file_hash);
            if ($ret === false)
            {
                throw new MFileopsException(
                                            FXP::t('Internal Server Error'),
                                            MConst::HTTP_CODE_500);
            }
            $this->handleFileMeta($path, $rev, $user_nick);
            
                        if (MFileVersions::updateRefCountById ( $rev ) == false) {
                throw new MFilesException ( FXP::t ( MConst::INTERNAL_SERVER_ERROR ), MConst::HTTP_CODE_500 );
            }
        }
                $mime_type = $version[0]["mime_type"];
        $response = array();
        $response["size"]           = MUtils::getSizeByLocale($locale, $size);
        $response["is_deleted"]     = true;
        $response["bytes"]          = intval($size);
        $response["thumb_exists"]   = MUtils::isExistThumbnail($mime_type, $size);
        $response["path"]           = $originalPath;
        $response["root"]           = $this->_root;
        $response["is_dir"]         = false;
        $response["mime_type"]      = $mime_type;
        $response["modified"]       = MUtils::formatIntTime(time());
        $response["rev"]            = strval($rev);
        $response["revision"]       = $rev;
        echo json_encode($response);
    }

    
    private function handleFileMeta($file_path, $version_id, $user_nick)
    {
                                $file_meta = MFileMetas::queryFileMeta($file_path, MConst::VERSION);
        if ($file_meta)
        {
            $meta_value = MUtils::getFileVersions($version_id, 
                                                    MConst::RESTORE, 
                                                    $this->_user_id, 
                                                    $user_nick,
                                                    $file_meta[0]["meta_value"]);
            $ret = MFileMetas::updateFileMeta(
                                        $file_meta->file_path, 
                                        MConst::VERSION, 
                                        $meta_value);
        }
        else 
        {
            $meta_value = MUtils::getFileVersions($version_id, 
                                                    MConst::RESTORE, 
                                                    $this->_user_id, 
                                                    $user_nick);
            $ret = MFileMetas::createFileMeta(
                                        $file_path, 
                                        MConst::VERSION, 
                                        $meta_value);
        }
        return $ret;
    }
}
?>